<%@ page import="java.io.*"%>
<%@ page import="javax.servlet.ServletOutputStream"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%!
	//define default buffer size 
	private static final int BUFF_SIZE = 2048;
%>
<%
	//To use this page, give 2 parameter
	//1: filename
	//2: the path of the file (without file name)
	//If no parameter, Print exception


	//Start to Read file
	try {
		//file name of the target
		String filename = request.getAttribute("filename").toString();
		//input filePath to read the file for the client download
		String filePath = request.getAttribute("filePath").toString();
		//Check input parament
		if(filename == null || filePath == null || filename.isEmpty() || filePath.isEmpty())
			throw new Exception("Incorrect input parameter");
		
		//filePath += "\\" + filename;
		
		File downloadFile = new File(filePath);
		if (!downloadFile.exists()) //throw error if file not found
			throw new FileNotFoundException("Download file: "
					+ filename + " Can't find");

		
		OutputStream op = response.getOutputStream();
		//get mimetype
		String mimetype = getServletConfig().getServletContext()
				.getMimeType(filename);
		if (mimetype == null || mimetype.isEmpty())
			mimetype = "application/outet-stream";
		
		//  Set the response and go!
		response.setContentType(mimetype);
		response.setContentLength((int) downloadFile.length());
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + filename + "\"");

		// Stream to the requester
		byte[] bbuf = new byte[BUFF_SIZE];
		int length = 0;
		DataInputStream in = new DataInputStream(new FileInputStream(
				downloadFile));

		while ((in != null) && (length = in.read(bbuf)) != -1) {
			op.write(bbuf, 0, length);
		}

		in.close();
		op.flush();
		op.close();

		out.clear();
		out = pageContext.pushBody();
	} catch (Exception e) {
		response.setContentType("text/html; charset=UTF-8");
		out.println(e.toString());
	}
%>